<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\ClockRecord;
use App\Models\Data;
use App\Models\Member;
use App\Models\Record;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class ClockController extends BaseController
{

    /**
     * 首页数据
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $build = ClockRecord::query();
        $pageSize = $request->input('pageSize', 50);
        $data = $build->paginate($pageSize);
        return $this->success($data);
    }

    public function recordIndex(Request $request)
    {
        $params = $request->all();

        $build = Record::query()
            ->leftJoin('ty_member', 'ty_member.member_id', '=', 'ty_record.member_id');

        //轮次

        if (isset($params['rounds']) && !empty($params['rounds'])){
            $build->where('rounds', $params['rounds']);
        }
        //工号
        if (isset($params['password']) && !empty($params['password'])){
            $build->where('password', $params['password']);
        }

        //姓名
        if (isset($params['name']) && !empty($params['name'])){
            $build->where('ty_member.name', $params['name']);
        }

        //时间
        if (isset($params['start_time']) && !empty($params['start_time'])){
            $build->whereBetween('ty_record.created_at', [date("Y-m-d H:i:s",$params['start_time']), date("Y-m-d H:i:s",$params['end_time'])]);
        }

        $pageSize = $request->input('pageSize', 50);
        $data = $build->paginate($pageSize);
        return $this->success($data);
    }

    public function onIndex(Request $request)
    {
        try {

            $params = $request->all();
            $build = ClockRecord::query()->where('status', 1)->first();
            $buildRecord = null;
            if ($build){
                $buildRecord = Record::query()->where('rounds', $build->rounds)->where('member_id', $params['member_id'])->first();
            }
            return $this->success(['clock_record' => $build, 'record' => $buildRecord, 'time' => time()]);
        }catch (\Exception $exception){
            echo $exception->getMessage();die;
            return $this->error(['1']);
        }

    }

    public function update($id, Request $request)
    {
        $params = $request->all();
        $clock = ClockRecord::query()->where('clock_id', $id)->first();
        if (!$clock){
            throw new AppException('find_clock_is_fail');
        }
        $paramsData['stop_time'] = $params['stop_time'];
        $result = ClockRecord::query()->where('clock_id', $id)->update($paramsData);
        return $this->success($result, '修改成功');
    }

    public function enable($id, Request $request)
    {
        $params = $request->all();
        $clock = ClockRecord::query()->where('clock_id', $id)->first();
        if (!$clock){
            throw new AppException('find_clock_is_fail');
        }

        $updateParams = ['status' => $params['status']];
        if ($params['status'] == 1){
            $updateParams['start_time'] = time();
        }

        if ($params['status'] == 2){
            //手动关闭
            $updateParams['status'] = $params['status'];
            $updateParams['stop_time'] = time();
        }
        $result = ClockRecord::query()->where('clock_id', $id)->update($updateParams);

        return $this->success($result, '操作成功');
    }

    public function clock($id, Request $request)
    {
        $Params = $request->all();

         if (!isset($Params['rounds'])){
             throw new AppException('find_clock_is_fail');
         }
         //判断是否结束
         $recordClock = ClockRecord::query()->where('rounds', $Params['rounds'])->first()->toArray();
         if ($recordClock['status'] != 1){
             return $this->error($recordClock, '对不起，当前轮次没开启');
         }
         $record = Record::query()->where('member_id', $id)->where('rounds', $Params['rounds'])->first();
         if ($record){
           return $this->error($record, '您已经打卡过咯');
         }

         $addParams['member_id'] = $id;
         $addParams['rounds'] = $Params['rounds'];
         $result = Record::query()->create($addParams);

         //处理member表打卡记录
        Member::query()->where('member_id', $id)->update(['record_' . $Params['rounds'] => 1]);
        return $this->success($result, '打卡成功');
    }

    /**
     * 导出excel
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws AppException
     */
    public function export(Request $request)
    {
        $params = $request->all();

        try {
            $directory = storage_path();
            $fileName = rand(1000, 9999) . time() . ".xlsx";//导出文件名
            $header = [
                'name' => '姓名', 'password' => '工号', 'code' => '员工编号','email' => '邮箱', 'record_1' => '第1轮', 'record_2' => '第2轮',
                'record_3' => '第3轮', 'record_4' => '第4轮', 'record_5' => '第5轮', 'record_6' => '第6轮', 'record_7' => '第7轮',
                'record_8' => '第8轮','record_9' => '第9轮', 'record_10' => '第10轮'
            ];
            $widthArray = ['A' => 10, 'B' => 10, 'C' => 10, 'D' => 10, 'E' => 10];
            $build = Member::query();
            if (isset($params['name'])){
                $build = $build->where('name', $params['name']);
            }

            if (isset($params['password'])){
                $build = $build->where('password', $params['password']);
            }
            $service = new ExcelExportService();
            $service->exportDataBySheet($directory, $fileName, $build, $header, 'handleRecord', 2000, $widthArray);
            return response()->download($directory . '/' . $fileName, '导出文件.xlsx', $headers = ['Content-Type' => 'application/zip;charset=utf-8']);
        } catch (\ Exception $exception) {
            echo $exception->getMessage();die;
            throw new AppException('export_fail');
        }
    }

}